package com.party.mobile.biz.member;

import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.party.authorization.manager.impl.RedisTokenManager;
import com.party.common.constant.Constant;
import com.party.common.utils.PartyCode;
import com.party.common.utils.PinyinUtil;
import com.party.core.exception.BusinessException;
import com.party.core.model.YesNoStatus;
import com.party.core.model.city.Area;
import com.party.core.model.member.Industry;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.member.ThirdPartyUser;
import com.party.core.model.system.SysConfig;
import com.party.core.service.city.IAreaService;
import com.party.core.service.member.IIndustryService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IThirdPartyUserService;
import com.party.core.service.system.IMobileVerifyService;
import com.party.core.service.system.ISysConfigService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.biz.verifyCode.VerifyCodeBizService;
import com.party.mobile.web.dto.login.output.CurrentUser;
import com.party.mobile.web.dto.login.output.MemberOutput;
import com.party.mobile.web.dto.member.input.FillInfoInput;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @ClassName MemberGroupBizService
 * @Description 机构用户业务处理
 * @Author yifeng
 * @Date 2019/10/9 16:26
 **/
@Service
public class MemberGroupBizService {
    @Autowired
    private CurrentUserBizService currentUserBizService;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private IMobileVerifyService mobileVerifyService;
    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private VerifyCodeBizService verifyCodeBizService;
    @Autowired
    private MemberBizService memberBizService;
    @Autowired
    private RedisTokenManager redisTokenManager;
    @Autowired
    private IThirdPartyUserService thirdPartyUserService;
    @Autowired
    private IAreaService areaService;
    @Autowired
    private IIndustryService industryService;

    public CurrentUser bindPhoneBiz2(String mobile, String vCode, String countryCode, HttpServletRequest request)
            throws BusinessException {
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        MemberGroup member = memberGroupService.get(currentUser.getId());

        // 加短信开关
        if (Strings.isNullOrEmpty(member.getMobile())) {
            boolean isVerify = sysConfigService.isVerifySms();
            if (isVerify) {
                //是否需要验证
                boolean isNeedVerify = mobileVerifyService.isNeedVerify(countryCode);
                if (isNeedVerify) {
                    //验证码验证
                    boolean verifyResult = verifyCodeBizService.verify(mobile, vCode);
                    if (!verifyResult) {
                        throw new BusinessException("手机号和验证码不匹配");
                    }
                }
            }

            //绑定手机号
            Map<String, Object> map = bindPhoneNew(mobile, request);
            //如果当前用户有合并操作需重新赋值
            if (null != map.get("memberId") && !map.get("memberId").equals(currentUser.getId())) {
                currentUser = currentUserBizService.getCurrentUserByToken((String) map.get("token"));
            }
        }
        return currentUser;
    }

    /**
     * 绑定手机 新
     * 2017-06-26
     *
     * @param mobile  手机号
     * @param request
     * @return 绑定手机
     */
    @Transactional
    public Map<String, Object> bindPhoneNew(String mobile, HttpServletRequest request) {
        CurrentUser curUser = currentUserBizService.getCurrentUser(request);
        MemberGroup curMember = memberGroupService.get(curUser.getId());
        //根据手机号查找用户
        MemberGroup mobileMember = memberGroupService.findByPhone(mobile, Constant.MEMBER_PERSONAL);
        Map<String, Object> output = Maps.newHashMap();
        //若用户存在
        if (null != mobileMember) {
            //当前用户不等于手机查到的用户
            if (!mobileMember.getId().equals(curMember.getId())) {
                //手机查找到的用户是合作商账户，不允许合并
                if (mobileMember.getIsPartner().equals(YesNoStatus.YES.getCode())) {
                    throw new BusinessException(PartyCode.PHONE_EXIST, "该手机已被绑定，请确认");
                }
                //如果当前用户是第三方授权账户
                if (CurrentUser.isThirdparty(curUser)) {
                    //查找第三方表中当前用户的记录
                    List<ThirdPartyUser> tUsers = thirdPartyUserService.getByMemberId(curUser.getId());
                    if (null != tUsers && tUsers.size() > 0) {
                        //更新第三方表中当前用户的记录为手机号查询到的用户
                        for (ThirdPartyUser tUser : tUsers) {
                            tUser.setMemberId(mobileMember.getId());
                            thirdPartyUserService.update(tUser);
                        }
                    }

                    //更新登录用户信息
                    //删除token
                    String oldToken = request.getHeader(com.party.authorization.utils.Constant.HTTP_HEADER_NAME);
                    redisTokenManager.delRelationshipByToken(oldToken);

                    //重新绑定token
                    String token = memberBizService.getToken(mobileMember, null);
                    output.put("token", token);
                    output.put("memberId", mobileMember.getId());
                } else {
                    /**
                     * 不是第三方用户,此处不处理合并操作，
                     * 因为现机构账号是使用用户名密码登录的，若合并其他账号的手机，会使当前用户混乱
                     */
                    throw new BusinessException(PartyCode.PHONE_EXIST, "该手机已被绑定，请确认");
                }
            }
        } else {//若用户不存在
            //更新当前用户的手机号为传入的手机
            curMember.setMobile(mobile);
            memberGroupService.update(curMember);
            output.put("memberId", curMember.getId());
        }
        return output;
    }

    public MemberOutput fillInfo(FillInfoInput fillInfoInput, String curId) throws Exception {
        //验证当前登录用户数据
        MemberGroup memberGroup = memberGroupService.get(curId);
        if (null == memberGroup) {
            throw new BusinessException(PartyCode.CURRENT_USER_DATA_ERROR, "当前用户数据错误,请重新登录");
        }
        //验证地区Area数据
        if (!Strings.isNullOrEmpty(fillInfoInput.getCity())) {

            Area area = areaService.get(fillInfoInput.getCity());
            if (null == area) {
                throw new BusinessException(PartyCode.AREA_DATA_ERROR, "当前输入的地区id有误，没有找到相应的地区信息");
            }
        }

        //验证行业industry数据
        if (!Strings.isNullOrEmpty(fillInfoInput.getIndustry())) {
            Industry industry = industryService.get(fillInfoInput.getIndustry());
            if (null == industry) {
                throw new BusinessException(PartyCode.INDUSTRY_DATA_ERROR, "当前输入的行业id有误，没有找到相应的行业信息");
            }
        }

        FillInfoInput.transform(memberGroup, fillInfoInput);
        //所有用户自主填写的内容都需过滤Emoji表情
        memberGroup.setRealname(PinyinUtil.filterEmoji(memberGroup.getRealname(), ""));
        memberGroup.setPinyin(PinyinUtil.hanziToPinyin(memberGroup.getRealname(), ""));
        memberGroup.setFullname(PinyinUtil.filterEmoji(memberGroup.getFullname(), ""));
        memberGroup.setCompany(PinyinUtil.filterEmoji(memberGroup.getCompany(), ""));
        memberGroup.setJobTitle(PinyinUtil.filterEmoji(memberGroup.getJobTitle(), ""));
        memberGroup.setWechatNum(PinyinUtil.filterEmoji(memberGroup.getWechatNum(), ""));

        memberGroupService.update(memberGroup);

        MemberOutput output = memberBizService.getLoginMember(memberGroup);

        return output;
    }
    /**
     * 获取行知公社用户id
     *
     * @return 行知公社用户id
     * @author yifeng
     * @date 10:08 2019/11/13
     **/
    public String getXzgsMemberId() {
        String memberId = "";
        // 获取行知公社参数配置
        SysConfig xzgsConfig = sysConfigService.findByCode("XZGSID");
        if (xzgsConfig == null) {
            //正式环境中行知公社机构ID
            memberId = "c94e89415d7d4611b706cecfc43af2ae";
        } else {
            memberId = xzgsConfig.getValue();
        }
        return memberId;
    }
}
